package com.jingshui.Service.imp;

import com.alibaba.fastjson.JSONObject;
import com.jingshui.Dao.UserDao;
import com.jingshui.Entity.User;
import com.jingshui.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import orm.base.Ex.BaseServiceEx;
import orm.utils.BeanToMapUtil;
import orm.utils.WxUtils;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ashin on 2017/9/28.
 */
@Service
@Scope("prototype")
public class UserServiceImp extends BaseServiceEx implements UserService {

    @Autowired
    UserDao userDao;

    @Autowired
    private WxUtils wxUtils;

    @Override
    public void init() {
        super.init(userDao);
    }

    @Override
    public String getOpenIdWxOauth(Map map, HttpSession session, String redirectUrl) throws Exception {
        String code = map.get("code").toString();
        JSONObject jsonObject = wxUtils.getWxUserInfo(code);
        if (jsonObject.getInteger("code") == sCode) {
            jsonObject = jsonObject.getJSONObject("data");
            String openId = jsonObject.getString("openid");
            String headIcon = jsonObject.getString("headimgurl");
            String wxName = jsonObject.getString("nickname");
            Map userMap = new HashMap();
            userMap.put("openId", openId);
            User user = userDao.selectp(userMap);
            if (user == null) {
                userMap.put("headIcon", headIcon);
                userMap.put("wxName", wxName);
                int ret = userDao.insertp(userMap);
                if (ret != -1) {
                    Map _userMap = new HashMap();
                    _userMap.put("openId", openId);
                    session.setAttribute("user", userDao.selectp(_userMap));
                }
            } else {
                session.setAttribute("user", user);
            }
            return "redirect:" + redirectUrl;
        } else {
            return "redirect:/user/404";
        }
    }

    @Override
    public JSONObject getUserInfo(HttpSession session) throws Exception {
        User user = (User) session.getAttribute("user");
        Map userMap = new HashMap();
        userMap.put("openId", user.getOpenId());
//        userMap.put("openId","otT_v1UJqMlsKlxe-gmVAGUNfQA4");
        return this.codeData(userDao.selectp(userMap));
    }

    @Override
    public JSONObject checkPassword(Map map, HttpSession session) throws Exception {
        if (map.get("password") != null && map.get("password").toString().equals("ja0810")) {
            User user = (User) session.getAttribute("user");
            user.setAuthen("1");
            session.setAttribute("user", user);
            return this.codeMess(sCode, "密码正确");
        } else {
            return this.codeMess(eCode, "密码错误");
        }
    }
}
